package cn.jingyuan.swan.gw.service.impl;

import cn.jingyuan.bee.fastjson.FastJsonUtils;
import cn.jingyuan.swan.cloud.core.Result;
import cn.jingyuan.swan.cloud.core.ResultUtils;
import cn.jingyuan.swan.gw.service.RouteService;
import cn.jingyuan.swan.gw.service.feign.GatewayRouteFeignService;
import cn.jingyuan.swan.system.model.dto.GatewayRouteDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class RouteServiceImpl implements RouteService {

    @Resource
    GatewayRouteFeignService gatewayRouteFeignService;

    @Override
    public Map<String, ZuulProperties.ZuulRoute> getRoutes() {
        Result<List<GatewayRouteDto>> routeResult = gatewayRouteFeignService.getRoutes();
        log.info("routeResult = {}", FastJsonUtils.json(routeResult));

        LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();
        if (ResultUtils.isSuccess(routeResult)) {
            return routesMap;
        }

        List<GatewayRouteDto> routes = routeResult.getData();
        for (GatewayRouteDto route : routes) {
            if (StringUtils.isEmpty(route.getPath())) {
                continue;
            }

            if (StringUtils.isEmpty(route.getServiceId()) && StringUtils.isEmpty(route.getUrl())) {
                continue;
            }

            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            BeanUtils.copyProperties(route, zuulRoute);
            zuulRoute.setId(route.getRouteName());

            routesMap.put(zuulRoute.getPath(), zuulRoute);
        }

        return routesMap;
    }

}
